package com.game.doudizhu.config;

import com.game.doudizhu.service.GameService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

@Component
public class WebSocketEventListener {
    
    private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);
    
    @Autowired
    private GameService gameService;
    
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    
    @EventListener
    public void handleWebSocketConnectListener(SessionConnectEvent event) {
        logger.info("收到新的WebSocket连接");
        SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
        String playerId = headers.getFirstNativeHeader("playerId");
        String roomId = headers.getFirstNativeHeader("roomId");
        
        if (playerId != null && roomId != null) {
            // 存储会话信息
            headers.getSessionAttributes().put("playerId", playerId);
            headers.getSessionAttributes().put("roomId", roomId);
            logger.info("玩家 {} 连接到房间 {}", playerId, roomId);
        }
    }
    
    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(event.getMessage());
        String playerId = (String) headers.getSessionAttributes().get("playerId");
        String roomId = (String) headers.getSessionAttributes().get("roomId");
        
        if (playerId != null && roomId != null) {
            logger.info("玩家 {} 断开连接，房间 {}", playerId, roomId);
            
            try {
                // 处理玩家断开连接
                gameService.handlePlayerDisconnect(Long.parseLong(playerId), Long.parseLong(roomId));
                
                // 通知房间其他玩家
                messagingTemplate.convertAndSend(
                    "/topic/room/" + roomId,
                    gameService.getRoomStatus(Long.parseLong(roomId))
                );
            } catch (NumberFormatException e) {
                logger.error("解析玩家ID或房间ID时出错: playerId={}, roomId={}", playerId, roomId);
            } catch (Exception e) {
                logger.error("处理玩家断开连接时出错", e);
            }
        }
    }
} 